import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "./store/user";
import axios from "axios";
import Home from "./views/Home.vue";
import Login from "./views/Login.vue";
import ColumnDetail from "./views/ColumnDetail.vue";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      name: "home",
      component: Home,
    },
    {
      path: "/login",
      name: "login",
      component: Login,
      // 若已登录，重定向到首页
      meta: { redirectAlreadyLogin: true },
    },
    {
      path: "/column/:id",
      name: "column",
      component: ColumnDetail,
    },
  ],
});

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const { requiredLogin, redirectAlreadyLogin } = to.meta;

  if (!userStore.isLogin) {
    if (userStore.token) {
      axios.defaults.headers.common.Authorization = `Bearer ${userStore.token}`;
      userStore
        .fetchCurrentUser()
        .then(() => {
          if (redirectAlreadyLogin) {
            next("/");
          } else {
            next();
          }
        })
        .catch((e) => {
          console.log("路由全局守卫出错：", e);
          userStore.logout();
          next("login");
        });
    } else {
      if (requiredLogin) {
        next("login");
      } else {
        next();
      }
    }
  } else {
    if (redirectAlreadyLogin) {
      next("/");
    } else {
      next();
    }
  }
});

export default router;
